package com.cloudkinto.service.operate.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.cloudkinto.common.utils.StringsUtil;
import com.cloudkinto.dao.UserDao;
import com.cloudkinto.entity.OperateRecordDo;
import com.cloudkinto.dao.OperateRecordDao;
import com.cloudkinto.entity.OrderAmazonDo;
import com.cloudkinto.entity.UserDo;
import com.cloudkinto.extentity.order.OperateRecordAddDto;
import com.cloudkinto.service.operate.OperateRecordService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.cloudkinto.common.web.PageResult;
import com.cloudkinto.common.web.SingleResult;

import com.cloudkinto.service.operate.vo.OperateRes;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.util.CollectionUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * service实现类
 * </p>
 *
 * @author zhangyy
 * @since 2020-07-09
 */
@Service
@Transactional(rollbackFor = Exception.class)//事务回滚
public class OperateRecordServiceImpl extends ServiceImpl<OperateRecordDao, OperateRecordDo> implements OperateRecordService {
    @Autowired
    private OperateRecordDao dao;
    @Autowired
    private UserDao userDao;

    @Override
    public SingleResult addInit() {
        return SingleResult.success("");
    }

    @Override
    public Object add(Object req, Long userId) {
        OperateRecordDo entityDo = new OperateRecordDo();
        BeanUtils.copyProperties(req, entityDo);
        handlerAddBefore(entityDo, userId);
        dao.insert(entityDo);
        return handlerAddAfter(entityDo);
    }

    //新增校验
    private void addCheck(Object req) {

    }

    //做新增之前要执行的业务定制处理
    private void handlerAddBefore(OperateRecordDo entityDo, Long userId) {
    }

    //将新增的do转换成要返回的实体
    private Object handlerAddAfter(OperateRecordDo entityDo) {
        Object res = new Object();
        BeanUtils.copyProperties(entityDo, res);
        return res;
    }

    @Override
    public SingleResult updateInit(Long id) {
        return SingleResult.success("");
    }

    @Override
    public Object update(Object req, Long userId) {
        /*OperateRecordDo entityDo = dao.selectById(req.getId());
        BeanUtils.copyProperties(req, entityDo);
        handlerUpdateBefore(entityDo, userId);
        dao.updateById(entityDo);
        return handlerUpdateAfter(entityDo);*/
        return null;
    }

    //编辑校验
    private void updateCheck(Object req) {

    }

    //做修改之前要执行的业务定制处理
    private void handlerUpdateBefore(OperateRecordDo entityDo, Long userId) {
    }

    //做修改之后要执行的业务定制处理
    private Object handlerUpdateAfter(OperateRecordDo entityDo) {
        Object res = new Object();
        BeanUtils.copyProperties(entityDo, res);
        return res;
    }

    @Override
    public int delete(Long id, Long userId) {
        OperateRecordDo entityDo = dao.selectById(id);
        handlerDeleteBefore(entityDo, userId);
        return dao.deleteById(id);
    }

    //做删除之前要执行的业务定制处理
    private void handlerDeleteBefore(OperateRecordDo entityDo, Long userId) {
    }

    @Override
    public Object detail(Long id) {
        OperateRecordDo entityDo = dao.selectById(id);
        Object res = new Object();
        BeanUtils.copyProperties(entityDo, res);
        return handlerDetailAfter(res);
    }

    //查询明细之后要执行的业务定制处理
    private Object handlerDetailAfter(Object res) {
        return res;
    }

    @Override
    public SingleResult pageInit() {
        return SingleResult.success("");
    }

    @Override
    public List<Object> getList(Map<String, String> map) {
        QueryWrapper<OperateRecordDo> wrapper = queryBuild(map);
        List<OperateRecordDo> list = this.list(wrapper);
        List<Object> result = handlerListAfter(list);
        return result;
    }

    @Override
    public PageResult getListPage(Map<String, String> map) {
        QueryWrapper<OperateRecordDo> wrapper = queryBuild(map);
        IPage<OperateRecordDo> page = pageInit(map);
        page = this.page(page, wrapper);
        List<Object> resList = handlerListAfter(page.getRecords());
        PageResult result = new PageResult(resList, (int) page.getCurrent(), (int) page.getSize(), (int) page.getTotal(), (int) page.getPages());
        return result;
    }

    @Override
    public List<OperateRes> getOperateList(Long thirdId, int type) {
        List<OperateRes> operateResList = new ArrayList<>();
        LambdaQueryWrapper<OperateRecordDo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(OperateRecordDo::getThirdId, thirdId).eq(OperateRecordDo::getType, type).orderByDesc(OperateRecordDo::getId);
        List<OperateRecordDo> operateRecordDos = dao.selectList(queryWrapper);
        if (!CollectionUtils.isEmpty(operateRecordDos)) {
            for (OperateRecordDo operateRecordDo : operateRecordDos) {
                OperateRes operateRes = new OperateRes();
                operateRes.setOperateTime(operateRecordDo.getOperateTime());
                if (StringUtils.isNotBlank(operateRecordDo.getContentValue()))
                    if (operateRecordDo.getContentValue().contains(operateRecordSeparator))
                        operateRes.setContent(StringsUtil.createI18Message(operateRecordDo.getContent(), operateRecordDo.getContentValue().split(operateRecordSeparator)));
                    else
                        operateRes.setContent(StringsUtil.createI18Message(operateRecordDo.getContent(), operateRecordDo.getContentValue()));
                else
                    operateRes.setContent(StringsUtil.createI18Message(operateRecordDo.getContent()));
                UserDo userDo = userDao.selectById(operateRecordDo.getOperateBy());
                if (userDo != null) {
                    operateRes.setOperateBy(userDo.getUserName() == null ? userDo.getUserAccount() :
                            userDo.getUserName());
                }
//                operateRes.setop
                operateResList.add(operateRes);
            }
        }
        return operateResList;
    }

    /**
     *
     * @param content
     * @param thirdId
     * @param userId
     * @param type    1：商品 2：入库单 3：出库单 4：亚马逊订单 5：乐天订单 6:fba转运订单 7 shopify订单 8退货
     * @return
     */
    @Override
    public boolean operateAddRecord(String content, Long thirdId, Long userId, int type) {
        OperateRecordDo operateRecordDo = new OperateRecordDo();
        operateRecordDo.setContent(content);
        operateRecordDo.setOperateTime(new Date());
        operateRecordDo.setOperateBy(userId);
        operateRecordDo.setType(type);
        operateRecordDo.setThirdId(thirdId);
        operateRecordDo.setDeleteFlag(0);
        dao.insert(operateRecordDo);
        return true;
    }

    @Override
    public boolean operateAddRecord(String content, Long thirdId, Long userId, int type, String detail) {
        OperateRecordDo operateRecordDo = new OperateRecordDo();
        operateRecordDo.setContent(content);
        operateRecordDo.setRemarks(detail);
        operateRecordDo.setOperateTime(new Date());
        operateRecordDo.setOperateBy(userId);
        operateRecordDo.setType(type);
        operateRecordDo.setThirdId(thirdId);
        operateRecordDo.setDeleteFlag(0);
        dao.insert(operateRecordDo);
        return true;
    }

    public static final String operateRecordSeparator = "!&";

    /**
     * contentValue 多个以 !& 隔开
     *
     * @param content
     * @param contentValue
     * @param thirdId
     * @param userId
     * @param type
     * @return
     */
    @Override
    public boolean operateAddRecordAndValue(String content, String contentValue, Long thirdId, Long userId, int type) {
        OperateRecordDo operateRecordDo = new OperateRecordDo();
        operateRecordDo.setContent(content);
        operateRecordDo.setContentValue(contentValue);
        operateRecordDo.setOperateTime(new Date());
        operateRecordDo.setOperateBy(userId);
        operateRecordDo.setType(type);
        operateRecordDo.setThirdId(thirdId);
        operateRecordDo.setDeleteFlag(0);
        dao.insert(operateRecordDo);
        return true;
    }

    @Override
    public void insertList(List<OperateRecordAddDto> list) {
        if (list.isEmpty()) {
            return;
        }
        dao.insertList(list);
    }

    //查询分页列表之后对列表数据的处理
    private List<Object> handlerListAfter(List<OperateRecordDo> list) {
        List<Object> result = new ArrayList<>();
        return result;
    }

    private IPage<OperateRecordDo> pageInit(Map<String, String> map) {
        IPage<OperateRecordDo> page = new Page();
        page.setSize(StringUtils.isNotBlank(map.get("pageSize")) ? Long.parseLong(map.get("pageSize")) : 10);
        page.setCurrent(StringUtils.isNotBlank(map.get("current")) ? Long.parseLong(map.get("current")) : 1);
        return page;
    }

    private QueryWrapper<OperateRecordDo> queryBuild(Map<String, String> map) {
        QueryWrapper<OperateRecordDo> wrapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(map.get("keyword"))) {
            wrapper.like("keyword", map.get("keyword"));
        }
        return wrapper;
    }


}
